import React from 'react'
import PropTypes from 'prop-types'
import { Form, Input, Select, Modal } from 'antd'
import {IEVersion} from 'utils/util';

const FormItem = Form.Item
const Option = Select.Option

const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 14,
  },
}

const modal = ({
  item = {},
  onOk,
  modalCancel,
  form: {
    getFieldDecorator,
    validateFields,
    getFieldsValue,
  },
  organizationList,
  parentOrganization,
  ...modalProps
}) => {
  const handleOk = () => {
    validateFields((errors) => {
      if (errors) {
        return
      }
      const data = {
        ...getFieldsValue(),
        key: item.key,
      }
      for(const key in data){
        if(data[key]===undefined){
          data[key]=''
        }
      }
      // parentId设置错误，并且类型不为Int
      if(data.parentId) {
        data.parentId = Number(data.parentId);
      }
      onOk(data)
    })
  }

  const modalOpts = {
    ...modalProps,
    onOk: handleOk,
    onCancel: modalCancel
  }

  return (
    <Modal {...modalOpts} style={IEVersion()?{right:"30%"}:{}}>
      <Form layout="horizontal">
        <FormItem label="机构名" hasFeedback {...formItemLayout}>
          {getFieldDecorator('name', {
            initialValue: item.name,
            rules: [
              {
                required: false,
              },
            ],
          })(<Input />)}
        </FormItem>
        <FormItem label="描述" hasFeedback {...formItemLayout}>
          {getFieldDecorator('describe', {
            initialValue: item.describe,
            rules: [
              {
                required: false,
              },
            ],
          })(<Input />)}
        </FormItem>
        <FormItem label="上级机构" hasFeedback {...formItemLayout}>
          {getFieldDecorator('parentId', {
            initialValue: parentOrganization,
            rules: [
              {
                required: false,
              },
            ],
          })(
            <Select
              showSearch
              optionFilterProp="children"
              filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            >
            {
              organizationList.length && organizationList.map(element => {
                if(item.id != element.id)
                return <Option value={`${element.id}`} key={element.id} type='option'>{element.name}</Option>
                else return
              })
            }
            </Select>
          )}
        </FormItem>
      </Form>
    </Modal>
  )
}

modal.propTypes = {
  form: PropTypes.object.isRequired,
  type: PropTypes.string,
  item: PropTypes.object,
  onOk: PropTypes.func,
}

export default Form.create()(modal)